﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPMonitor.DataModel.Report;
using System.IO;
using System.Text;

namespace NPMonitor.Web
{
    public class ReportHelper
    {
        public static void XlsDownload(List<ReportData> list)
        { 
            HSSFWorkbook book=new HSSFWorkbook();
            ISheet sheet = book.CreateSheet();

            int rowIndex=6;

            foreach (var legend in list[0].list)
            {
                var row = sheet.CreateRow(rowIndex++);

                int cellIndex = 1;
                row.CreateCell(cellIndex).SetCellValue(legend.BeginTime);
                
                foreach (var item in list)
                {
                    cellIndex++;
                    foreach (var point in item.list)
                    {
                        if (point.BeginTime == legend.BeginTime)
                        {
                            string cellValue=point.AverageTime != 0 ? string.Format("{0:N3}", point.AverageTime) : "-";
                            row.CreateCell(cellIndex).SetCellValue(cellValue);
                            
                        }
                    }
                }
            }

            HttpContext.Current.Response.AppendHeader("Content-Disposition ", "attachment;filename=Excel.xls ");
            HttpContext.Current.Response.Charset = "UTF-8 ";
            HttpContext.Current.Response.ContentEncoding = Encoding.Default;
            HttpContext.Current.Response.ContentType = "application/ms-excel "; 
            MemoryStream stream = new MemoryStream();
            book.Write(stream);
            HttpContext.Current.Response.AddHeader("Content-Length", stream.ToArray().Length.ToString());
            stream.WriteTo(HttpContext.Current.Response.OutputStream);
            stream.Close();
            HttpContext.Current.Response.OutputStream.Flush();
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }
}